﻿#region
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using EndlessDownloader;
using EndlessDownloader.Engine;

#endregion

namespace EndlessDownloaderEx
{
    public partial class ParallelForm : Form
    {
        public ParallelForm()
        {
            InitializeComponent();
        }

        private const int Count = 10;

        private void button2_Click(object sender, EventArgs e)
        {
            Stopwatch watch = Stopwatch.StartNew();

            for (int i = 1; i <= Count; i++)
            {
                GetValue(i);
            }

            MessageBox.Show(watch.Elapsed.ToString());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private static void GetValue(int page)
        {
            string url = "http://kv86.tumblr.com/page/" + page;

            WebClient webClient = new WebClient();
            string html = webClient.DownloadString(url);
            var imageUrls = ImageSourceParser.Instance.ExtractImageUrl(html, true);
            var i2 = imageUrls;
        }

        private void Print(string item)
        {
            listBox1.InvokeIfNeeded(() =>
                                        {
                                            listBox1.Items.Add(item);
                                            listBox1.SelectedIndex = listBox1.Items.Count - 1;
                                        });
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var range = Enumerable.Range(1, Count);

            Stopwatch watch = Stopwatch.StartNew();

            Parallel.ForEach(range, page => { GetValue(page); });

            e.Result = watch;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Stopwatch watch = (Stopwatch) e.Result;

            MessageBox.Show(watch.Elapsed.ToString());
        }
    }
}